package com.gao.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @Projectname springboot-06-security
 * @Filename SecurityConfig
 * @Author an
 * @Data 2022/8/14 10:01
 * @Description TODO
 */
//AOP：拦截器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {


    //授权
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问，功能也只有对应有权限的人才能访问
        http.authorizeHttpRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认到登录页面
        //定制登录页面
        http.formLogin().loginPage("/tologin")
                .loginProcessingUrl("/login")
                .usernameParameter("user")
                .passwordParameter("pwd");

        //防止网站攻击：get，post
        http.csrf().disable();//关闭csrf功能,登陆失败可能存在的原因

        //注销功能
        http.logout().logoutSuccessUrl("/");


        //开启记住我功能，默认两周
        //自定义接受前端的参数
        http.rememberMe().rememberMeParameter("remember");
    }


    //认证
    //springboot 2.1.x 可以直接使用
    //密码编码： PasswordEncoder
    //在springSecurity5.0+新增了很多的加密方法
    //.passwordEncoder(new BCryptPasswordEncoder())
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

       //这些数据正常应该从数据库中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }


}
